package com.application.service;

import com.application.common.OrderStatus;
import com.application.model.Order;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Service;
import com.platform.mvc.base.BaseService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service(name = StatsService.serviceName)
public class StatsService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(StatsService.class);

	public static final String serviceName = "statsService";

	/**
	 * @param num
	 * @param size
	 * @param clientStatus
	 * @param key
	 * @param sD
	 * @param eD 结束时间
	 * @return
	 */
	public Page<Map<String, Object>> findOrderList(int num, int size, List<Integer> clientStatus, String key, String sD, String eD) {

		String qS = getQueryStr(clientStatus, key, sD, eD);
		/**
		 * 1.查询时间分页参数
		 */
		String sql = "SELECT order_date from t_order where 1=1 "+ qS+" group by order_date order by order_date desc";
		String limit = " limit " + size + " offset " + (num-1)*size;
		List<Integer> dateList = Db.query(sql + limit);
		int count = Db.queryLong("select count(*) from (" + sql + ") a").intValue();

		StringBuffer sb = new StringBuffer();
		for (Integer date : dateList) {
			sb.append(date + ",");
		}
		sb.append("-1");

		StringBuffer query = new StringBuffer();
		query.append("select id,order_no,order_status,total_amount,create_time,order_date ");
		query.append(" from t_order where 1=1 " + qS);
		query.append(" and order_date in (" + sb.toString() + ") order by id desc ");

		List<Order> orderList = Order.dao.find(query.toString());


		//封装客户端通用订单状态
		orderList.forEach(o-> o.put("client_order_status", OrderStatus.clientMap.get(o.getOrder_status())));

		//		Page<Order> page = Order.dao.paginate(num, size, sel, from);

		/**
		 * 2.封装数据
		 */
		List<Map<String, Object>> resultList = new ArrayList<>();
		for (Integer date : dateList) {
			Map<String, Object> map = new LinkedHashMap<>();
			List<Order> itemList = new ArrayList<>();
			BigDecimal totalAmount = new BigDecimal(0);
			for (Order order : orderList) {
				if(date.intValue() == order.getOrder_date()){
					itemList.add(order);
					totalAmount = totalAmount.add(order.getTotal_amount());
				}
			}
			map.put("dateStr", date);
			map.put("totalAmount", totalAmount.floatValue());
			map.put("dataList", itemList);
			resultList.add(map);
		}


		Page<Map<String, Object>> page = new Page<>(resultList, num, size, count/size + 1, count);

		return page;
	}

	private String getQueryStr(List<Integer> clientStatus, String key, String startDate, String endDate) {
		StringBuffer query = new StringBuffer(500);
		String qStatus = Order.getStatusSqlString(clientStatus);
		query.append(qStatus);
		if(StrKit.notBlank(key)) {
			query.append(" and (instr(order_username, '"+ key +"') >0 or instr(order_no, '"+ key +"') >0 ) ");
		}

		if(StrKit.notBlank(startDate)) {
			query.append(" and create_time >= '" + startDate + "'");
		}

		if(StrKit.notBlank(endDate)) {
			query.append(" and create_time <= '" + endDate + "'");
		}

		return query.toString();
	}

	public List<Record> queryProductSalesList(String startDate, String endDate, int productId) {
		List<Record> list;

		String sql = "SELECT DATE_FORMAT(a.create_time,'%Y-%m-%d') as date, sum(pay_amount) as amount, \n" +
				" sum(product_spec) as spec, product_spec_unit as spec_unit " +
				"from t_order a left join t_order_item b on a.id = b.order_id \n" +
				"where delete_time is null " +
				"and order_status in (10, 20, 21) and a.create_time >=? and a.create_time <=? and product_id = ? \n" +
				"GROUP BY date,product_spec_unit order by date";

		list = Db.find(sql, startDate, endDate, productId);

		return list;
	}
}
